import 'dart:convert';
import 'dart:io';
import 'dart:io';
import 'dart:ui';

import 'package:core_package/core_package.dart';
import 'package:core_package/share/my_font_weight.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/main/protocol_page.dart';
import 'package:flutter_app_unionad/request/login_request.dart';
import 'package:flutter_app_unionad/ui/login/binding_mobile_page.dart';
import 'package:flutter_app_unionad/ui/login/login_for_password_page.dart';
import 'package:flutter_app_unionad/ui/login/widget/login_input_widget.dart';
import 'package:flutter_app_unionad/ui/login/widget/privacy_protocol_widget.dart';
import 'package:flutter_app_unionad/view_model/page_manager_view_model.dart';
import 'package:fluwx/fluwx.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';
import 'package:flutter_unionad/flutter_unionad.dart' as FlutterUnionad;
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

class LoginForMobilePage extends StatefulWidget {
  static const String routeName = "/loginForMobilePage";

  final bool isLaunch;

  const LoginForMobilePage({Key? key, this.isLaunch = false}) : super(key: key);

  @override
  _LoginForMobilePageState createState() => _LoginForMobilePageState();
}

class _LoginForMobilePageState extends State<LoginForMobilePage> {
  bool isOpen = true;
  bool selectProtocol = false;
  String? mobile;
  String? code;
  bool installWeChat = false;
  bool firstInstall = false;

  void agreeProtocol() async {
    HttpRequest.init(url: "https://www.51uuid.com"); //线上
    final f = await FlutterUnionad.FlutterUnionad.register(
      androidAppId: "5059869",
      //穿山甲广告 Android appid 必填
      iosAppId: "5039476",
      //穿山甲广告 ios appid 必填
      useTextureView: true,
      //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView 选填
      appName: "汼汼生活",
      //appname 必填
      allowShowNotify: true,
      //是否允许sdk展示通知栏提示 选填
      allowShowPageWhenScreenLock: true,
      //是否在锁屏场景支持展示广告落地页 选填
      debug: false,
      //测试阶段打开，可以通过日志排查问题，上线时去除该调用 选太难
      supportMultiProcess: true,
      //是否支持多进程，true支持 选填
      // directDownloadNetworkType: [
      //   FlutterUnionad.FlutterUnionadNetCode.NETWORK_STATE_3G,
      //   FlutterUnionad.FlutterUnionadNetCode.NETWORK_STATE_4G,
      //   FlutterUnionad.FlutterUnionadNetCode.NETWORK_STATE_WIFI
      // ],
    );

    ShareSDKRegister register = ShareSDKRegister();
    register.setupWechat('wx4344437e7b2e124f', '030576778c54620985823f88d74bb34d', 'https://51uuid.com/');
    SharesdkPlugin.regist(register);
    registerWxApi(appId: "wx4344437e7b2e124f", doOnAndroid: true, doOnIOS: true, universalLink: "https://51uuid.com/");
  }

  void install() async {
    if (Platform.isIOS) {
      setState(() {});
    }

    SharesdkPlugin.isClientInstalled(ShareSDKPlatforms.wechatSession).then((value) {
      print(value); //{state: installed}
      if (Platform.isIOS) {
        if (mounted)
          setState(() {
            installWeChat = value;
          });
      } else {
        if (value['state'] == 'installed') {
          if (mounted)
            setState(() {
              installWeChat = true;
            });
        }
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    print("window.physicalSize  ${window.physicalSize}");
    print('LoginForMobilePage');
    String? agreeProtocol = UserCacheUil.getString('Protocol');
    if ((agreeProtocol == null || agreeProtocol.length == 0) && !firstInstall) {
      //加载屏幕第一帧后在显示弹框
      WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
        showProtocolWidget();
      });
    } else {
      install();
    }
  }

  void showProtocolWidget() {
    firstInstall = true;
    ShowCenterAlertDialog.showAlert(
      context,
      radius: 8,
      width: 296,
      height: 500,
      builder: (ctx) {
        return PrivacyProtocolWidget();
      },
    ).then(
      (value) {
        if (value) {
          //同意
          UserCacheUil.setString("Protocol", 'Protocol');

          agreeProtocol();

          install();
        } else {}
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        body: GestureDetector(
          child: buildContent(context),
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
        ),
      ),
    );
  }

  Widget buildContent(BuildContext context) {
    print('buildContent');
    return Container(
      height: SizeFill.screenHeight,
      width: SizeFill.screenWidth,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(
            MyAssetsImages.setAssetsImagesPath("icon_login_bg"),
          ),
          fit: BoxFit.fill,
        ),
      ),
      child: SingleChildScrollView(
        child: Container(
          child: Column(
            children: [
              SizedBox(height: SizeFill.statusHeight! + SizeFill.setRx(20)),
              Row(
                children: [
                  Expanded(child: MySizeBox()),
                  InkWell(
                    onTap: () {
                      NavigatorUtil.push(context, LoginForPasswordPage.routeName);
                    },
                    child: Text(
                      "密码登录",
                      style: TextStyle(
                        color: MyColors.formHex("#272727FF"),
                        fontSize: MyFont.font14,
                      ),
                    ),
                  ),
                  SizedBox(width: 20),
                ],
              ),
              SizedBox(height: SizeFill.setRx(40)),
              Image.asset(
                MyAssetsImages.setAssetsImagesPath("icon_logo_1"),
                width: SizeFill.setRx(131.67),
                height: SizeFill.setRx(124.33),
              ),
              SizedBox(height: SizeFill.setRx(48)),
              Text(
                "让 生 活 更 美 好",
                style: TextStyle(
                  fontFamily: "assets/fonts/ZhanKuWenYiTi_2.ttf",
                  fontWeight: MyFontWeight.regular,
                  color: MyColors.formHex("#272727FF"),
                  fontSize: SizeFill.setRx(16),
                ),
              ),
              MySizeBox(height: 30),
              buildInputContent(),
              MySizeBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildInputContent() {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(SizeFill.setRx(7)),
      ),
      margin: EdgeInsets.symmetric(horizontal: SizeFill.setRx(17)),
      child: Padding(
        padding: EdgeInsets.only(
          left: SizeFill.setRx(37),
          right: SizeFill.setRx(37),
          top: SizeFill.setRx(30),
          bottom: SizeFill.setRx(30),
        ),
        child: buildInputList(),
      ),
    );
  }

  Widget buildInputList() {
    return Column(
      children: [
        Text(
          "手机验证码登录",
          style: TextStyle(
            fontSize: MyFont.font14,
            color: MyColors.formHex("#272727FF"),
            fontWeight: MyFontWeight.bold,
          ),
        ),
        MySizeBox(height: 30),
        LoginInputWidget(
          maxLength: 11,
          placeholder: "请输入手机号",
          leftIcon: "icon_account",
          keyboardType: TextInputType.number,
          inputTextTapChange: (value) {
            mobile = value;
          },
        ),
        MySizeBox(height: 13),
        Row(
          children: [
            Expanded(
              child: LoginInputWidget(
                maxLength: 6,
                placeholder: "请输入验证码",
                leftIconWidget: Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: SizeFill.setRx(10)),
                  child: Text(
                    "验证码",
                    style: TextStyle(
                      color: MyColors.formHex("#272727FF"),
                      fontSize: MyFont.font12,
                    ),
                  ),
                ),
                keyboardType: TextInputType.number,
                inputTextTapChange: (value) {
                  code = value;
                },
              ),
            ),
            MySizeBox(width: 5),
            Container(
              color: MyColors.formHex("#F8BA35FF"),
              child: ShowSendCodeWidget(
                sendCodeType: SendCodeType.register,
                fontSize: MyFont.font12,
                textColor: Colors.white,
                norTextColor: Colors.white,
                minWidth: SizeFill.setRx(96),
                height: SizeFill.setRx(40),
                phone: mobile,
                bgColor: MyColors.formHex("#F8BA35FF"),
                sendCodeOnTap: sendCodeOnTap,
              ),
            )
          ],
        ),
        MySizeBox(height: 30),
        buildButton("登录", () {
          loginOnTap();
        }),
        MySizeBox(height: 30),
        buildThirdLogin(),
        // MySizeBox(height: 13),
        // buildButton("注册", () {
        //   registerOnTap();
        // }),
        MySizeBox(height: 12),
        buildProtocolWidget(),
      ],
    );
  }

  Widget buildThirdLogin() {
    List icons = [];

    if (installWeChat) {
      icons.add('login_wechat_login');
    }

    if (Platform.isIOS) {
      icons.add('login_mac_login');
    }
    if (icons.length == 0) return Container();
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(icons.length, (index) {
        return Padding(
          padding: EdgeInsets.only(right: index == (icons.length - 1) ? 0 : SizeFill.setRx(38)),
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              thirdLoginOnTap(icons[index]);
            },
            child: Image.asset(
              MyAssetsImages.setAssetsImagesPath(
                icons[index],
              ),
              width: SizeFill.setRx(25),
              height: SizeFill.setRx(25),
            ),
          ),
        );
      }),
    );
  }

  Widget buildButton(String title, Function() onTap) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        onTap();
      },
      child: Container(
        width: SizeFill.setRx(267),
        height: SizeFill.setRx(40),
        decoration: BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              MyAssetsImages.setAssetsImagesPath("icon_button_bg_1"),
            ),
          ),
        ),
        alignment: Alignment.center,
        child: Text(
          title,
          style: TextStyle(
            color: MyColors.formHex("#FFFFFFFF"),
            fontSize: MyFont.font14,
            fontWeight: MyFontWeight.bold,
          ),
        ),
      ),
    );
  }

  Widget buildProtocolWidget() {
    TextStyle blackTS = TextStyle(
      color: MyColors.color_43_44_48,
      fontSize: 11.px,
      fontWeight: MyFontWeight.regular,
    );
    TextStyle blueTS = TextStyle(
      color: Color.fromARGB(255, 15, 187, 222),
      fontSize: 11.px,
      fontWeight: MyFontWeight.regular,
    );
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            setState(() {
              selectProtocol = !selectProtocol;
            });
          },
          child: Container(
            padding: EdgeInsets.all(SizeFill.setRx(5)),
            child: Image.asset(
              MyAssetsImages.setAssetsImagesPath(selectProtocol ? "icon_select" : "icon_unselect"),
              width: SizeFill.setRx(14),
              height: SizeFill.setRx(14),
            ),
          ),
        ),
        SizedBox(width: 3),
        Expanded(
          child: Text.rich(
            TextSpan(
              children: [
                TextSpan(
                  text: '我已阅读，且完全通用并接受',
                  style: blackTS,
                ),
                // TextSpan(
                //   text: '《中国移动认证服务条款》',
                //   style: blueTS,
                // ),
                // TextSpan(
                //   text: '和',
                //   style: blackTS,
                // ),
                TextSpan(
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      //
                      NavigatorUtil.push(context, ProtocolPage.routeName, arguments: 1);
                    },
                  text: '《注册协议》',
                  style: blueTS,
                ),
                TextSpan(
                  text: '和',
                  style: blackTS,
                ),
                TextSpan(
                  text: '《服务隐私协议》',
                  style: blueTS,
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      NavigatorUtil.push(context, ProtocolPage.routeName, arguments: 0);
                    },
                ),
              ],
            ),
            // strutStyle: StrutStyle(forceStrutHeight: true, height: 0.58, leading: 1),
          ),
        )
      ],
    );
  }

  void loginOnTap() {
    if (!selectProtocol) {
      ShowToastWidget.showToast(msg: "请同意相关协议");
      return;
    }
    if (!isPhoneString(mobile)) {
      ShowToastWidget.showToast(msg: "手机号格式不对");
      return;
    }
    if (code == null) {
      ShowToastWidget.showToast(msg: "验证码不能为空");
      return;
    }
    if (!isCode(code!, length: 6)) {
      ShowToastWidget.showToast(msg: "请6位验证码");
      return;
    }

    ProgressDialog.showProgress(context);
    endKeyboard(context);
    LoginRequest.login(code: code, phone: mobile).then((value) {
      ProgressDialog.dismiss(context);
      print(value);
      if (value != null && value) {
        PagesManagerViewModel.updateType(context, PagesManagerType.app);
      }
    });
  }

  void registerOnTap() {
    // NavigatorUtil.push(context, RegisterPage.routeName);
  }

  void thirdLoginOnTap(String type) async {
    print('thirdLoginOnTap $type');
    if (!selectProtocol) {
      ShowToastWidget.showToast(msg: "请同意相关协议");
      return;
    }
    if (type == "login_wechat_login") {
      // 微信登录
      SharesdkPlugin.getUserInfo(ShareSDKPlatforms.wechatSession,
          (SSDKResponseState state, dynamic map, SSDKError error) {
        SharesdkPlugin.cancelAuth(
            ShareSDKPlatforms.wechatSession, (SSDKResponseState state, dynamic map, SSDKError error) {});
        if (state == SSDKResponseState.Success) {
          if (Platform.isIOS) {
            String openid = map['rawData']['openid'];
            String nickname = map['rawData']['nickname'];
            String avatar = map['rawData']['headimgurl'];

            authOpenId(openid, nickname, avatar);
          } else {
            Map dbInfo = json.decode(map['dbInfo']);
            String openid = dbInfo['openid'];
            String nickname = dbInfo['nickname'];
            String avatar = dbInfo['icon'];

            print(openid);
            print(nickname);
            print(avatar);
            authOpenId(openid, nickname, avatar);
          }
        } else {
          ShowToastWidget.showToast(msg: '微信授权失败');
        }
      });
    } else if (type == "icon_alipay") {
      //支付宝登录
    } else if (type == "login_mac_login") {
      //苹果登录
      final s = await SignInWithApple.isAvailable();
      if (!s) {
        ShowToastWidget.showToast(msg: '当前系统版本不支持苹果登录');

        return;
      }
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );
      if (credential.identityToken != null) {
        authOpenId(credential.userIdentifier ?? '', credential.givenName ?? '', 'avatar');
      } else {
        ShowToastWidget.showToast(msg: '登录失败');
      }

      // debugPrint(
      //     "facebook userInfo : userId=${credential.userIdentifier}   email=${credential
      //         .identityToken}  giveName=${credential.givenName}   familyName=${credential.familyName}");
    } else if (type == "icon_iphone") {
      //手机验证码登录
      // NavigatorUtil.push(context, BindingMobilePage.routeName);
    }
  }

  // ignore: missing_return
  Future<bool> sendCodeOnTap() async {
    if (!isPhoneString(mobile)) {
      ShowToastWidget.showToast(msg: "手机号码格式不对");
      return false;
    }
    return LoginRequest.sendCode(type: 10, phone: mobile);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  void authOpenId(String openId, String nickName, String headImg) {
    ProgressDialog.showProgress(context);
    LoginRequest.getUserByOpenId(openId).then((value) {
      ProgressDialog.dismiss(context);
      if (value == 1) {
        //成功
        PagesManagerViewModel.updateType(context, PagesManagerType.app);
      } else if (value == 2) {
        //绑定
        NavigatorUtil.push(context, BindingMobilePage.routeName, arguments: {
          'avatar': headImg,
          'openid': openId,
          'username': nickName,
        });
      }
    });
  }

  int last = 0;

  Future<bool> _onWillPop() {
    int now = DateTime.now().millisecondsSinceEpoch;
    if (now - last > 8000) {
      last = DateTime.now().millisecondsSinceEpoch;
      ShowToastWidget.showToast(msg: "再次点击返回退出应用", gravity: ToastGravity.BOTTOM);
      return Future.value(false);
    } else {
      return Future.value(true);
    }
  }
}
